import { FC, useState, useEffect } from 'react';
import styles from './style.less';

import classnames from 'classnames';

import PdfPreviewer from '@/components/PdfPreviewer';

interface Iprops {
  title: string;
  previewUrl: string;
  downloadUrl: string;
  visible: boolean;
  onClose: () => void;
}
const Dialog: FC<Iprops> = (props) => {
  const { title, previewUrl, downloadUrl, visible, onClose } = props;
  const [selfVisible, setSelfVisible] = useState<boolean>(false);
  const downloadFile = () => {
    const tag = document.createElement('a');
    tag.href = downloadUrl;
    tag.download = `${title}.pdf`;
    document.body.appendChild(tag);
    tag.click();
    document.body.removeChild(tag);
  };
  useEffect(() => {
    const inter = setTimeout(() => {
      setSelfVisible(visible);
    }, 200);
    return () => {
      clearTimeout(inter);
    };
  }, [visible]);
  return visible || selfVisible ? (
    <div className={styles.dialog_container}>
      <div
        className={classnames(
          styles.content,
          visible && selfVisible ? styles.open : null,
        )}
      >
        <p className={styles.title}>{title}</p>
        <div className={styles.preview_container}>
          {previewUrl || downloadUrl ? (
            <PdfPreviewer fileUrl={previewUrl} width={1000} height={570} />
          ) : null}
        </div>
        <div
          className={classnames(styles.button, styles.close)}
          onClick={onClose}
        >
          关闭
        </div>
        <div
          className={classnames(styles.button, styles.download)}
          onClick={() => downloadFile()}
        >
          下载
        </div>
      </div>
    </div>
  ) : null;
};
export default Dialog;
